import logging
from django.core.cache import cache
from user.helpers import generate_captcha, send_email, is_email_valid
from django.http import JsonResponse
from django.views.generic.edit import FormView
from django.views.generic import DetailView
from django.contrib.auth import login, authenticate, logout
from django.shortcuts import redirect, render
from django.contrib import messages
from .forms import LoginForm, RegisterForm
from .models import User

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)s: %(message)s', datefmt='[%m/%d/%Y %H:%M:%S]')
logger = logging.getLogger(__name__)


def login_view(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('/')
            else:
                messages.error(request, "用户名或密码不正确!")
        else:
            messages.error(request, "用户名或密码不正确!")

    return render(
        request,
        "user/login.html",
        {"form": LoginForm}
    )


class RegisterView(FormView):
    template_name = 'user/register.html'
    form_class = RegisterForm
    success_url = '/'

    def form_valid(self, form):
        user = form.save()
        login(self.request, user)
        return super().form_valid(form)


def logout_view(request):
    logout(request)
    return redirect('/')


def captcha_view(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        if is_email_valid(email):
            captcha = generate_captcha()
            # logger.debug(captcha)
            send_email(recipient=email, captcha=captcha)
            cache.set(email, captcha, 600)  # 600s
            return JsonResponse({'msg': f'send captcha to {email} success!'}, status=200)

        return JsonResponse({'msg': f'send captcha to {email} faild!'}, status=400)


class UserDetailView(DetailView):
    context_object_name = 'user'
    queryset = User.objects.all()
    template_name = 'user/profile.html'
